<template>
  <div style="width: 100%; height: 100vh; background-color: dodgerblue; overflow: hidden">
    <!--overflow: hidden去掉边距-->
    <div style="width: 400px; margin: 150px auto">
      <!--auto表示居中-->
      <div style="color: #cccccc; font-size: 30px; text-align: center; padding: 30px">欢迎登录</div>
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="form.username" :prefix-icon="UserFilled" placeholder="请输入用户名" />


        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="form.password" show-password :prefix-icon="Lock" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button v-if="isLogin" style="width: 100%" type="primary" @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="isLogin"
            style="width: 100%"
            type="primary"
            @click="() => $router.push('/register')"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
// @ts-ignore
import { UserFilled, Lock } from '@element-plus/icons-vue'

import request from '../utils/request'
// import register from "@/views/Register.vue";
import { useRouter } from 'vue-router'
import { ref, unref } from 'vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const form = ref<Record<string, any>>({
  images: undefined
})

// const user = ref<Record<string, any>>({
//   images: undefined
// })

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const isLogin = ref(true)
const formRef = ref<any>(null)

const login = () => {
  formRef.value?.validate((valid: any) => {
    // 验证请求，只有在输入了账号密码才能发送请求
    // form要与el-form ref="form"命名的名字一样
    if (valid) {
      request.post('/user/login', unref(form)).then((res) => {
        console.log(res)
        if (res.code === '200') {
          ElMessage.success('登录成功')
          isLogin.value = false
          // 登录成功后跳转到首页

          sessionStorage.setItem('user', JSON.stringify(res.data)) // 获取用户信息
          router.push('/') // 登录成功后页面跳转到首页
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
</script>

<style scoped></style>
